package com.fh.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Lp
 * @create 2021-03-08 13:53
 */
public class OssUtil {


    /**
     * 阿里云oss文件上传
     *
     * @param file
     * @throws IOException
     */
    public static String uploadFile(MultipartFile file) throws IOException {


        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LTAI4GEtd6bFoG14Mfy7toD6";
        String accessKeySecret = "xyauxmyaFMJeYAa2TuGTM4EagiZXj4";

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);


        String oldName = file.getOriginalFilename();

        String newName = UUID.randomUUID().toString() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));


// 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
        PutObjectRequest putObjectRequest = new PutObjectRequest("test-food", newName,
                new ByteArrayInputStream(file.getBytes()));


// 上传字符串。
        ossClient.putObject(putObjectRequest);

// 关闭OSSClient。
        ossClient.shutdown();


        return "https://test-food.oss-cn-beijing.aliyuncs.com/" + newName;
    }


}


